import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
//组件
import { ElMessage } from 'element-plus'


//常量路由/异步路由/任意路由
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes';

//引入发请求的函数
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl/login';

//引入lodash
import _ from 'lodash';
import router from '@/router';


const findUserAsyncRoutes = (allAsyncRoutes: any, routes: any) => {
  return allAsyncRoutes.filter((item: any) => {
    //一级路由
    if (routes.indexOf(item.name) != -1) {
      //子路由
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoutes(item.children, routes);
      }
      return true;
    }
  })
}



export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: '',
    menuRoutes: [],
    buttonsList: []
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password });
        this.token = result.token;
        setToken(result.token);
        return 'ok'
      } catch (error) {
        return Promise.reject('失败');
      }
    },

    async getInfo() {
      try {
        //携带token
         let result = await reqUserInfo();
         console.log(result);
        this.name = result.name;
        this.avatar = result.avatar;
        this.buttonsList = result.buttons;
        let userRegisterAsyncRoute = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes), result.routes);
        this.setRoute([...userRegisterAsyncRoute, anyRoute]);
        this.menuRoutes = [...staticRoutes, ...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error);
      }
    },


    setRoute(registerRoute: any) {
      registerRoute.forEach((item: any) => {
        router.addRoute(item);
      })
    },
    //退出登录按钮
    async reset() {

      try {
        //退出登录请求
        await reqLogOut();
        //删除本地存储的token
        removeToken();
        this.token = ''
        this.name = ''
        this.avatar = ''
        //重置路由
        this.resetRoute();
        return 'ok';
      } catch (error) {
        return Promise.reject(error);
      }

    },
    //重置路由方法
    resetRoute() {
      //获取用户全部路由
      let allRoutes = router.getRoutes();
      //退出登录清除全部路由
      allRoutes.forEach((item: any) => {

        router.removeRoute(item.name);
      });
      staticRoutes.forEach((item: any) => {
        router.addRoute(item);
      });
    }
  },
});
